package com.block.test.service.impl;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.applet.service.AppletConfigInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.db.entity.AppletConfigInfo;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.ChannelBaseInfo;
import com.block.test.service.IMiniPageJumpInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
public class MiniPageJumpInfoServiceImpl implements IMiniPageJumpInfoService {


    public static final String GENERATE_SCHEME_URL = "https://api.weixin.qq.com/wxa/generatescheme?access_token=";
    public static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    public static final String APPID = "wx0b9a900434927c1d";
    public static final String SECRET = "b6d41160b41b68c0d1f51115e8f6b801";

    private static final String REDIS_KEY_ACCESS_TOKEN = "wechat:access_token";

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    AppletConfigInfoService appletConfigInfoService;

    @Override
    public JSONObject miniPageJumpInfo(ChannelBaseInfo channelBaseInfo) {

//        AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
//        channelBaseInfo = channelBaseInfoService.getSelectByChannelCode(channelBaseInfo.getChannelCode());
        JSONObject jsonObject = new JSONObject();

        //如果类型是小程序则返回正常参数

        return handleH5Response(jsonObject,channelBaseInfo);
    }

    @Override
    public JSONObject miniPageJumpH5Info(ChannelBaseInfo channelBaseInfo) {
        JSONObject jsonObject = new JSONObject();
        if(!StrUtil.equals(channelBaseInfo.getPageType(),"h5_to_mini")){
            return jsonObject;
        }
        String redisKey1 = "APPLET::JUMP::H5::APPID";
        String redisKey2 = "APPLET::JUMP::H5::SECRET";
        String appId = stringRedisTemplate.opsForValue().get(redisKey1);
        String secret = stringRedisTemplate.opsForValue().get(redisKey2);
        String redisKey = "applet_jump_h5" + appId + secret;
        String accessToken = stringRedisTemplate.opsForValue().get(redisKey);
        if(accessToken == null){
            String url = String.format(ACCESS_TOKEN_URL, appId, secret);
            String response = restTemplate.getForObject(url, String.class);
            JSONObject data = JSONObject.parseObject(response);
            if (data.containsKey("access_token")){
                accessToken = data.getString("access_token");
            }else {
                throw new RuntimeException("获取 Access Token 失败：" + data.getString("errmsg"));
            }
        }
        stringRedisTemplate.opsForValue().set("applet_jump_h5", accessToken, 7200, TimeUnit.SECONDS);
        //发起scheme调用
        JSONObject requestBody = new JSONObject();
        JSONObject jumpWxa = new JSONObject();
        jumpWxa.put("path", "pages/index/index");
        jumpWxa.put("query", "ch="+ channelBaseInfo.getChannelCode());
        jumpWxa.put("env_version","release");
        requestBody.put("jump_wxa", jumpWxa);
        String urlToken = GENERATE_SCHEME_URL + accessToken;
        String response1 = restTemplate.postForObject(urlToken, requestBody.toJSONString(),String.class);
        JSONObject result = JSONObject.parseObject(response1);
        Integer errcode = result.getInteger("errcode");
        if(errcode == 0){
            AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
            String openlink = result.getString("openlink");
            jsonObject.put("openlink", openlink);
            jsonObject.put("gzhLogo", appletConfigInfo.getGzhLogo());
            jsonObject.put("gzhName", appletConfigInfo.getGzhName());
            jsonObject.put("gzhQrCode", appletConfigInfo.getGzhQrCode());
        }
        return jsonObject;
    }


    private JSONObject handleH5Response(JSONObject jsonObject,ChannelBaseInfo channelBaseInfo) {
        //如果为h5页面 需要跳转小程序页面 则调用微信
        //获取小程序登录token
        String redisKey = REDIS_KEY_ACCESS_TOKEN + APPID + SECRET;
        String accessToken = stringRedisTemplate.opsForValue().get(redisKey);
        if(accessToken == null){
            String url = String.format(ACCESS_TOKEN_URL, APPID, SECRET);
            String response = restTemplate.getForObject(url, String.class);
            JSONObject data = JSONObject.parseObject(response);
            if (data.containsKey("access_token")){
                accessToken = data.getString("access_token");
            }else {
                throw new RuntimeException("获取 Access Token 失败：" + data.getString("errmsg"));
            }
        }
        stringRedisTemplate.opsForValue().set(REDIS_KEY_ACCESS_TOKEN, accessToken, 7200, TimeUnit.SECONDS);
        return buildSchemeRequest(jsonObject, channelBaseInfo, accessToken);
    }

    private JSONObject buildSchemeRequest(JSONObject jsonObject, ChannelBaseInfo channelBaseInfo, String accessToken) {
        //发起scheme调用
        JSONObject requestBody = new JSONObject();
        JSONObject jumpWxa = new JSONObject();
        jumpWxa.put("path", "pages/gzh/gzh");
        jumpWxa.put("query", "ch="+ channelBaseInfo.getChannelCode());
        jumpWxa.put("env_version","release");
        requestBody.put("jump_wxa", jumpWxa);
        String urlToken = GENERATE_SCHEME_URL + accessToken;
        String response1 = restTemplate.postForObject(urlToken, requestBody.toJSONString(),String.class);
        JSONObject result = JSONObject.parseObject(response1);
        Integer errcode = result.getInteger("errcode");
        if(errcode == 0){
            AppletConfigInfo appletConfigInfo = appletConfigInfoService.selectAppletByChannelCode(channelBaseInfo.getChannelCode());
            String openlink = result.getString("openlink");
            jsonObject.put("openlink", openlink);
            jsonObject.put("gzhLogo", appletConfigInfo.getGzhLogo());
            jsonObject.put("gzhName", appletConfigInfo.getGzhName());
            jsonObject.put("gzhQrCode", appletConfigInfo.getGzhQrCode());
        }
        return jsonObject;
    }
}
